package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource(name = "accountDao")
    private AccountDao accountDao;

    @Transactional
    @Override
    public void transfer(String fromActno, String toActno, double amount) {
        Account fromAccount = accountDao.selectActNo(fromActno);
        Account toAccount = accountDao.selectActNo(toActno);
        if (fromAccount == null || toAccount == null) {
            throw new RuntimeException("为查询到该用户！！！");
        }
        if (fromAccount.getBalance() < amount) {
            throw new RuntimeException("余额不足！！！");
        }
        fromAccount.setBalance(fromAccount.getBalance() - amount);
        toAccount.setBalance(toAccount.getBalance() + amount);
        int count = accountDao.update(fromAccount);
        count += accountDao.update(toAccount);
        if (count != 2) {
            throw new RuntimeException("转账失败！！！");
        }
    }
}
